package microgame.toolset.serverconfig;

import Core.Log4j2;
import Core.WebSocketServer;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

public class ServerConfig {
    private static ServerConfig instance;

    private String userServerRpcHost;
    private int userServeRpcPort;

    public static ServerConfig Instance() {
        if (instance == null) {
            instance = new ServerConfig();
        }
        return instance;
    }

    public String GetUserServeRpcHost() {
        return userServerRpcHost;
    }

    public int GetUserServeRpcPort() {
        return userServeRpcPort;
    }

    public void Init() {
        try {
            File file = new File(WebSocketServer.class.getProtectionDomain().getCodeSource().getLocation().toURI());
            String absolutePath = file.getAbsolutePath();
            String folderPath;
            if (absolutePath.contains(".")) {
                folderPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
            }
            else {
                //IDE里面，没有后缀
                folderPath = absolutePath;
            }
            String xmlFile = folderPath + File.separator + "serverConfig.xml";

            File f = new File(xmlFile);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(f);
            NodeList nl = doc.getElementsByTagName("config");
            if (nl.getLength() < 1) {
                Log4j2.LOGGER.error("serverConfig.xml format error，must have config root。");
                return;
            }

            userServerRpcHost = doc.getElementsByTagName("userserverpchost").item(0).getFirstChild().getNodeValue();
            userServeRpcPort = Integer.parseInt(doc.getElementsByTagName("userserverpcport").item(0).getFirstChild().getNodeValue());
        }
        catch (Exception e) {
            Log4j2.LOGGER.error(e.toString());
        }
    }
}
